/*
 * ScrapLotAction.java
 *
 * Created on June 9, 2002, 12:54 AM
 */

package com.scalar.chiptrack.operations.process.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.engineering.dao.EngineeringDAO;
import com.scalar.chiptrack.operations.LotView;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.utils.Mailer;

/**
 *
 * @author  Mallikarjun
 * @version 1.0
 */
public class LotMergeAction extends ChipTrackAction{
       private static final String ACTION_NAME = "/splitMergeLot.do";
       public ActionForward execute (ActionMapping mapping,
                                      ActionForm form,
                                      HttpServletRequest request,
                                      HttpServletResponse response)
                                      throws Exception {

            DBTransaction dbt = null;
            boolean success = false;
            String lotaction = request.getParameter("lotaction");
            HashMap errors = new HashMap();
            HashMap info = new HashMap();
            String from = "";
            LotView lview = null;
            String mergedLotNo = null;

            // Added by veeru on 14th July 2004
            HttpSession hs = request.getSession();
            User user = (User)hs.getAttribute(SessionKeys.USER_KEY);
            if ( user == null )
            {
                hs.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString () );
                return ( mapping.findForward ( "login" ) );
            }
            // End of Added by veeru
            if((lotaction != null) &&(lotaction.equalsIgnoreCase("LOT_MERGE_SAVE"))){

            	//HttpSession hs = request.getSession(false);
            	lview = (LotView)hs.getAttribute(SessionKeys.LOT_VIEW);
                //User user = (User)hs.getAttribute(SessionKeys.USER_KEY);
                ArrayList mergeLots = new ArrayList();
                String mergeQty = request.getParameter("totalMergeQty");
                // Modified by veeru on 1st July 2004
                mergedLotNo = request.getParameter( "mergeLotNo" );
                String lot[] = request.getParameterValues("lot");
                String qty[] = request.getParameterValues("quantity");

                for ( int i = 0; i < lot.length; i++ )
                {
                    if(  lot[ i ] != null &&  !lot[ i ].equalsIgnoreCase("") &&  qty[ i ] != null &&  !qty[ i ].equalsIgnoreCase("") )
                    {
                        mergeLots.add( lot[i]+"#"+qty[i] );
                    }
                }

                /*String lot1 = request.getParameter("lot1");
                String lot2 = request.getParameter("lot2");
                String lot3 = request.getParameter("lot3");
                String lot4 = request.getParameter("lot4");

                String qty1 = request.getParameter("quantity1");
                String qty2 = request.getParameter("quantity2");
                String qty3 = request.getParameter("quantity3");
                String qty4 = request.getParameter("quantity4");

                if( ( (lot1 != null) && (!lot1.equalsIgnoreCase("")) ) ||
		            ( (lot2 != null) && (!lot2.equalsIgnoreCase("")) ) ||
		            ( (lot3 != null) && (!lot3.equalsIgnoreCase("")) ) ||
		            ( (lot4 != null) && (!lot4.equalsIgnoreCase("")) )    ){
                         if((lot1 != null) && (!lot1.equalsIgnoreCase(""))){
                                if(EngineeringDAO.isLotRunning(lot1)){
                                	mergeLots.add(lot1+"#"+qty1);
                                }else{
                                        request.setAttribute("errorMessage", (lot1+" Lot is not Running"));
                                        request.setAttribute("lview", lview);
                                        request.setAttribute("from", "LOT_MERGE_SAVE");
                                        return mapping.findForward("show");
                                }
                         }

                         if((lot2 != null) && (!lot2.equalsIgnoreCase(""))){
                                if(EngineeringDAO.isLotRunning(lot2)){
                                	mergeLots.add(lot2+"#"+qty2);
                                }else{
                                        request.setAttribute("errorMessage", (lot2+"  Lot is not Running"));
                                        request.setAttribute("lview", lview);
                                        request.setAttribute("from", "LOT_MERGE_SAVE");
                                        return mapping.findForward("show");
                                }
                         }

                         if((lot3 != null) && (!lot3.equalsIgnoreCase(""))){
                                if(EngineeringDAO.isLotRunning(lot3)){
                                	mergeLots.add(lot3+"#"+qty3);
                                }else{
                                        request.setAttribute("errorMessage", (lot3+" Lot is not Running"));
                                        request.setAttribute("lview", lview);
                                        request.setAttribute("from", "LOT_MERGE_SAVE");
                                        return mapping.findForward("show");
                                }
                         }

                         if((lot4 != null) && (!lot4.equalsIgnoreCase(""))){
                                if(EngineeringDAO.isLotRunning(lot4)){
                                	mergeLots.add(lot4+"#"+qty4);
                                }else{
                                        request.setAttribute("errorMessage", (lot4+" Lot is not Running"));
                                        request.setAttribute("lview", lview);
                                        request.setAttribute("from", "LOT_MERGE_SAVE");
                                        return mapping.findForward("show");
                                }
                         }

                   }else{

                   	request.setAttribute("errorMessage", "At least one lot should be Running state");
                        request.setAttribute("lview", lview);
                        return mapping.findForward("show");
                   }*/

                try{
	        	dbt = DBTransaction.getInstance();
	                dbt.begin();
	                int pullId = 0;
	                int alarmId = 0;
                        String error_code = "";

                        Iterator it = mergeLots.iterator();

                        /*while(it.hasNext()){
                                System.out.println("Values = " + (String)it.next());
                        }

                        System.out.println("Merge Qty = "+ mergeQty); */

	                //operation 1
	                 error_code = EngineeringDAO.mergeLots(dbt, lview, mergeLots, mergeQty);

                        if("SUCCESS".equalsIgnoreCase(error_code)){

	                	success = true;
                        }else{
                                request.setAttribute("errorMessage", error_code);
                                success = false;
                        }

	            }catch(Exception e){

	                e.printStackTrace();
	                throw new ScalarException("LotMergeAction failed", e);

	            }finally{

	                if(success){

	                    dbt.commit();
                        String mailTo = user.getEmail();
                        //String mailFrom = "chiptrac@scalarsoft.com";
                        String mailFrom = user.getEmail();
                        String subject = "Lots Merge into : "+lview.getLotNumber();
                        String message = mailFormat(lview, mergeLots, mergeQty,mergedLotNo);
                        info.put("Lot Merge ", "Successfully Saved");
                        try
                        {
                            Mailer.send(mailFrom, mailTo, subject, message, Mailer.CONTENT_TYPE_HTML);
                            info.put("E-mail ", "Mail has been sent");
                        }
                        catch( Exception e )
                        {
                            errors.put("E-mail ", "Could not sent Mail");
                        }

                    }else{
	                    dbt.rollback();
	                }

	                //hs.removeAttribute(SessionKeys.LOT_VIEW);
                        //hs.removeAttribute(SessionKeys.SPLIT_LIST);
	            }

	            if(!errors.isEmpty()) {
                    request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);
                }
                if(!info.isEmpty()) {
                    request.setAttribute(SessionKeys.INFO_MESSAGES, info);
                }


                    return mapping.findForward("engConfirm");
            }

            return mapping.findForward("success");
       }

       private String mailFormat(LotView lview, ArrayList mergeLots, String mergeQuantity,String mergeLotno) {

	        StringBuffer buf = new StringBuffer();

           buf.append ("<table border='0'>\n");
	        buf.append ("<th colspan='4'><h2>Lot Merge Info</h2></th>\n");
	        buf.append ("<tr><td width='20%'><b>Lot Number</b></td>\n");
	        buf.append ("<td width='40%'>" + lview.getLotNumber() + "</td>\n");
	        buf.append ("<td width='20%'><b>Product Name</b></td>\n");
	        buf.append ("<td width='20%'>" + lview.getPartNumber() + "</td>\n");
	        buf.append ("</tr><tr><td width='20%'><b>Current Process</b></td>\n");
	        buf.append ("<td width='40%'>" + lview.getCurrentProcess() + "</td>\n");
	        buf.append ("<td width='20%'><b>Date Code</b></td>\n");
	        buf.append ("<td width='20%'>" + lview.getDateCode() + "</td>\n");
	        buf.append ("</tr><tr><td width='20%'><b>Vendor & Location</b></td>\n");
	        buf.append ("<td width='40%'>" + lview.getVendorLocationName() + "</td>\n");
	        buf.append ("<td width='20%'><b>Status</b></td>\n");
	        buf.append ("<td width='20%'>" + lview.getStatus() + "</td>\n");
	        buf.append ("</tr><tr><td width='20%'><b>Date In</b></td>\n");
	        buf.append ("<td width='40%'>" + lview.getDateIn() + "</td>\n");
	        buf.append ("<td width='20%'><b>Quantity In</b></td>\n");
	        buf.append ("<td width='20%'>" + lview.getQuantityIn() + "</td>\n");
	        buf.append ("</tr><tr><td width='20%'><b>Date Out</b></td>\n");
	        buf.append ("<td width='40%'>" + lview.getDateOut() + "</td>\n");
	        buf.append ("<td width='20%'><b>Quantity Out</b></td>\n");
	        buf.append ("<td width='20%'>" + lview.getQuantityOut() + "</td>\n");
	        buf.append ("</tr><tr><td width='20%'><b>Current Yield</b></td>\n");
	        buf.append ("<td width='40%'>" + lview.getCurrentYield() + "</td>\n");
	        buf.append ("<td width='20%'>&nbsp;</td>\n");
		    buf.append ("<td width='20%'>&nbsp;</td>\n");
	        buf.append ("</tr><tr><td colspan='4'>&nbsp;</td></tr>\n");

                Iterator it =  mergeLots.iterator();

                while(it.hasNext())
                {
                        StringTokenizer st = new StringTokenizer((String)it.next(), "#");

                        while(st.hasMoreTokens()){
                          String mergeLotId = st.nextToken();
                        buf.append("<tr><td width='20%'><b>Merged Lot Number</b></td>\n");
		                buf.append("<td width='40%'>" +  mergeLotno + "</td>\n");
                        buf.append("<td width='20%'><b>Merged Quantity</b></td>\n");
		                buf.append("<td width='20%'>" + st.nextToken() + "</td></tr>\n");
                        }
                }
           //buf.append("<table border='0' width='100%' align=right>\n");
           buf.append("<tr><td width='20%'><b>&nbsp;</b></td>\n");
           buf.append("<td width='40%'>&nbsp;</td>\n");
           buf.append("<td width='20%'><b>Total Quantity</b></td>\n");
           buf.append("<td width='20%'>" + mergeQuantity + "</td></tr>\n");

           buf.append ("</table>\n");

	        return buf.toString();
    }
}
